import { AppDataSource } from '../config/database';
import { AuthorizationCode } from '../entity/AuthorizationCode';
import { AccessToken } from '../entity/Accesstoken';
import { BrandStrategy } from '../brand/strategyFactory';
import * as path from 'path';
import * as fs from 'fs';
import axios from "axios";

const brandConfigPath = path.resolve(__dirname, '../../brand-config.json');
const BrandConfig = JSON.parse(fs.readFileSync(brandConfigPath, 'utf-8'));

export class MockThirdParty implements BrandStrategy {
  private appId: string;
  private appSecret: string;

  constructor(appId: string, appSecret: string) {
    this.appId = appId;
    this.appSecret = appSecret;
  }

  // 模拟绑定操作
  async exchangeToken(code: string): Promise<{ access_token: string; expires_in: number }> {
    const config = BrandConfig[this.appId];
    if (!config || config.app_secret !== this.appSecret) {
      throw new Error('Invalid app credentials');
    }

    const codeRepo = AppDataSource.getRepository(AuthorizationCode);
    const tokenRepo = AppDataSource.getRepository(AccessToken);

    const authCode = await codeRepo.findOne({where: {code}, relations: ['user']});
    if (!authCode || Date.now() - authCode.createdAt.getTime() > 600_000) {
      throw new Error('Invalid or expired authorization code');
    }

    const token = Math.random().toString(36).substr(2, 16);
    await tokenRepo.save({
      userId: authCode.userId,
      appId: this.appId,
      token,
      expiresAt: new Date(Date.now() + 3600_000 * 24)
    });

    return {
      access_token: token,
      expires_in: 24
    };
  }

  // 实现 refreshToken 方法
  async refreshToken(userId: string, oldToken: string): Promise<{ access_token: string; expires_in: number }> {
    const tokenRepo = AppDataSource.getRepository(AccessToken);

    // 验证旧令牌是否有效
    const existingToken = await tokenRepo.findOne({
      where: {userId, token: oldToken, appId: this.appId}
    });

    if (!existingToken || existingToken.expiresAt < new Date()) {
      throw new Error('Invalid or expired token');
    }

    // 生成新令牌
    const newToken = Math.random().toString(36).substr(2, 16);
    await tokenRepo.save({
      userId,
      appId: this.appId,
      token: newToken,
      expiresAt: new Date(Date.now() + 3600_000 * 24) // 24小时有效期
    });

    // 返回新令牌
    return {
      access_token: newToken,
      expires_in: 24
    };
  }

  // 模拟解绑流程
  async revokeToken(token: string): Promise<boolean> { // 修改返回类型
    const tokenRepo = AppDataSource.getRepository(AccessToken);
    const result = await tokenRepo.delete({token, appId: this.appId});

    // 返回操作结果（受影响行数 > 0 表示成功）
    return result.affected !== 0;
  }

  // 模拟刷新token流程
  async generateAuthorizationCode(userId: string): Promise<string> {
    const codeRepo = AppDataSource.getRepository(AuthorizationCode);
    const code = Math.random().toString(36).substr(2, 8).toUpperCase();
    await codeRepo.save({userId, code, createdAt: new Date()});
    return code;
  }

// 获取品牌设备信息
  async getDeviceList(accessToken: string): Promise<{ did: string; name: string; type: string; online: boolean}[]> {
    // 验证accessToken
    const tokenRepo = AppDataSource.getRepository(AccessToken);
    const tokenRecord = await tokenRepo.findOne({
      where: {token: accessToken, appId: this.appId}
    });

    if (!tokenRecord || tokenRecord.expiresAt < new Date()) {
      throw new Error('Invalid or expired access token');
    }

    // 获取品牌名
    const config = BrandConfig[this.appId];
    if (!config) {
      throw new Error('Invalid app configuration');
    }
    const brand = config.brand;

    try {
      let response;
      if (brand === 'xiaomi') {
        // 调用小米设备API
        response = await axios.get('http://localhost:3000/api/xiaomi/devices', {
          headers: {
            'access_token': accessToken,
            'app_id': this.appId
          }
        });

        // 转换小米设备格式
        return response.data.data.devices.map((device: any) => ({
          did: device.did,
          name: device.name,
          type: device.type
        }));

      } else if (brand === 'midea') {
        // 调用美的设备API
        response = await axios.get('http://localhost:3000/api/midea/devices', {
          headers: {
            'Authorization': `Bearer ${accessToken}`,
            'ClientId': this.appId
          }
        });

        // 转换美的设备格式
        return response.data.data.applianceList.map((device: any) => ({
          did: device.virtualId,
          name: device.name,
          type: device.type
        }));
      } else {
        throw new Error(`Unsupported brand: ${brand}`);
      }
    } catch (error: any) {
      if (error.response) {
        // API返回的错误
        throw new Error(`API Error: ${error.response.data.message || error.response.statusText}`);
      } else if (error.request) {
        // 请求已发出但没有响应
        throw new Error('No response from device API');
      } else {
        // 其他错误
        throw new Error(`Device API request failed: ${error.message}`);
      }
    }
  }

}
